/**
 * 吐槽详情页
 */
let ventId = 0,isLike = false, currentPageNo = 1,commentPageSize = 2,moreVentPageNo = 1,isHasMore = true;
$(function() {
    initVentObj();
    initFollowVent();
    //返回顶部
    $('.user-top').click(function () {
        document.body.scrollIntoView();
    }).mouseover(function () {
        $(this).children('.top').addClass('arrow');
    }).mouseout(function () {
        $(this).children('.top').removeClass('arrow');
    });
    //点赞
    $('.like-vent').click(function () {
        //如果还没有点赞
        if (!isLike){
            likeForVent();
        }
    });
    //去评论
    $('.go-comment').click(function () {
        //跳转到点赞分享的地方
        $('body,html').animate({scrollTop: $("#likeShare").offset().top},666);
    });
    //保存评论
    $('.btn-save-comment').click(function () {
        submitVentComment(this);
    });
    //需要过666毫秒再获取documentTop、readTop的高度，否则取得的高度不对
    setTimeout(function () {
        let readTop = $('.recommend-read')[0].offsetTop,windowHeight = $(window).height(), windowScrollTop = $(window).scrollTop();;
        //当页面内容太少，导致windowHeight >= readTop(浏览器窗口高度>.recommend-read距离浏览器顶端的高度)时，需要及时加载评论
        if ((windowScrollTop + windowHeight) >= readTop){
            listOneLevelComment();
            recommendMoreVent();
            return;
        }
        //监听滚动条位置
        $(window).scroll(function () {
            windowScrollTop = $(window).scrollTop();
            //如果滚动条滚动到class=recommend-read时、且还未初始化，开始加载评论信息，并解绑滚动条监听事件
            if ((windowScrollTop + windowHeight) > readTop){
                listOneLevelComment();
                recommendMoreVent();
                $(window).unbind('scroll');
            }
        });
    },666);
    //更多1级评论
    $('#moreComment').click(function () {
        currentPageNo ++;
        if ($(this).hasClass('read-more')){
            listOneLevelComment();
        }
    });
});

/**
 * 初始化吐槽对象数据
 */
function initVentObj() {
    let ventObjUrl = location.href, ventParamArr = ventObjUrl.split('?');
    if (ventParamArr.length < 2){
        alert('没查询到您要找的吐槽信息，可能已删除或仅发布人自己可见');
        return;
    }
    ventId = ventParamArr[1];
    ventId = ventId.split('#')[0];
    $.ajax({
        type: "POST",
        async: true,
        url: "/ventIndex/getIndexVent",
        dataType: 'json',
        data:{ventId: ventId,ventStatus: 0},
        success: function (ventResult) {
            setVentHtml(ventResult.ventObj);
        },
        error: function() {
        	alert("当前系统繁忙，请稍候再试");
        }
    });
}

/**
 * 根据吐槽信息加载评论信息
 */
function listOneLevelComment() {
    $.ajax({
        type: "POST",
        async: true,
        url: "/ventIndex/listOneLevelComment",
        dataType: 'json',
        data:{ventId: ventId,pageNo: currentPageNo, pageSize: commentPageSize,start: 0,twoPageSize:3},
        success: function (commentPi) {
            setVentCommentHtml(commentPi);
        },
        error: function() {
            alert("当前系统繁忙，请稍候再试");
        }
    });
}
/**
 * 设置吐槽对象HTML
 * @param ventObj 吐槽对象
 */
function setVentHtml(vo) {
    if (isNull(vo)){
        alert('您查找的吐槽数据不存在，或仅吐槽人自己可见，或被删除，请换个吐槽信息查询');
        return;
    }
    let un = vo.userNick, userHome = $('#userNickHome');
    $('title,.title').text(vo.title);
    $('.other-info span').each(function () {
        $(this).text(vo[this.id]);
    });
    $('.like-num').text(vo.likeTotal);
    $('.content').html(vo.content);
    isLike = vo.userLikeNum > 0;
    if (isLike){
        setLiked();
    }
    $('#ventUser').text(un);
    $('#ventTo').text(vo.ventTo);
    //如果是匿名
    if (vo.isAnonymous == 1){
        userHome.removeAttr('href');
    }else {
        userHome.attr('title',un + '的主页');
        userHome.attr('href','hisHome.html?' + vo.userId);
    }
}
/**
 * 设置吐槽评论集合HTML
 * @param piComment 评论PageInfo对象
 */
function setVentCommentHtml(piComment) {
    let commentList = piComment.list, commentListSize = commentList.length;
    for (let g = 0; g < commentListSize; g ++){
        appendOneLevelComment(commentList[g]);
    }
    //如果没有下一页
    if (!piComment.hasNextPage){
        $('#moreComment').removeClass('read-more').addClass('no-more').text('没有评论了');
    }
}
/**
 * 给吐槽数据点赞
 */
function likeForVent() {
    $.ajax({
        type: "POST",
        async: true,
        url: "/vent/saveVentLike",
        dataType: 'json',
        data:{ventId: ventId},
        success: function (vlData) {
            setVentLike(vlData);
        },
        error: function (vlData) {
            setVentLike(vlData);
        }
    });
}

/**
 * 设置吐槽点赞
 * @param vlData 点赞结果
 */
function setVentLike(vlData) {
    //如果没登录，则提示登录
    if (vlData.status == -1) {
        showLogin();
        return;
    }
    let likeTotal = $('#likeTotal').text();
    $('.like-num').text(parseInt(likeTotal) + 1);
    setLiked();
    isLike = true;
}
function showLogin() {
    $('.show-login,.page-mask').show();
}
/**
 * 设置已点赞
 */
function setLiked() {
    $('#likeTotal').css('background-position-y','-30px').parent().removeAttr('href');
    $('#likeShare .like-vent').addClass('liked');
    $('.like-vent').css('cursor','default');
}
function goLogin() {
    sessionStorage.setItem('backUrl','ventObj.html?' + ventId);
    location.href = 'ventLogin.html';
}

/**
 * 提交吐槽评论数据
 */
function submitVentComment(btnSubmitVC) {
    let btnVC = $(btnSubmitVC),commentTextArea = $('#' + btnVC.attr('textareaId'));
    let commentContent = commentTextArea.val();
    if (commentContent.length < 4){
        alert('评论字符不能小于4位');
        return;
    }
    setButtonStatus(btnSubmitVC,true,'提交中...');
    commentContent = filterXSS(commentContent);
    let replyCommentId = btnVC.attr('replyCommentId');
    $.ajax({
        type: 'post',
        url : '/ventComment/saveVentComment',
        dataType: 'json',
        timeout: 120000,
        data: {
            'parentCommentId': btnVC.attr('parentCommentId'),
            'parentCommentUserId': btnVC.attr('parentCommentUserId'),
            'ventId': ventId,
            'replyCommentId': replyCommentId,
            'replyCommentUserId': btnVC.attr('replyCommentUserId'),
            'content': commentContent,
            'commentLevel': btnVC.attr('commentLevel')
        },
        success: function(saveResult) {
            let r = saveResult.status;
            if(r == 1){
                let me = JSON.parse(localStorage.getItem('me')),d = new Date(),
                    dateStr = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDay() + ' ' +
                        d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(),
                    parentCommentId = btnVC.attr('parentCommentId'),userNick = btnVC.attr('userNick'),
                appendCommentObj = {
                    id: saveResult.id,
                    parentCommentId: parentCommentId,
                    replyCommentId: replyCommentId,
                    replyCommentUserNick: userNick,
                    userId: me.userId,
                    userNick: me.nickName,
                    createTime: dateStr,
                    content: commentContent,
                    likeTotal: 0
                };
                //如果父评论ID>0，说明是二级评论
                if (parentCommentId > 0){
                    appendTwoLevelComment(appendCommentObj);
                } else {
                    appendOneLevelComment(appendCommentObj);
                }
                commentTextArea.val('');
            }else if (r == -2) {
                alert('未获取到评论参数，请刷新页面再试');
            }else if(r == -1){
                alert("未登录，请您登录后再吐槽");
                showLogin();
            }else {
                alert("抱歉，系统繁忙，请稍候再试");
            }
            setButtonStatus(btnSubmitVC,false,'提交');
        },
        error: function () {
            alert("抱歉，系统开小差了，请稍候再试");
            setButtonStatus(btnSubmitVC,false,'提交');
        }
    });
}

/**
 * 添加一级评论HTML
 * @param commentObj 一级评论对象
 */
function appendOneLevelComment(commentObj) {
    let commentId = commentObj.id,twoLevelCommentArr = commentObj.twoLevelCommentList,
        twoLevelHtmlArr = [],cUserId = commentObj.userId;
    if (twoLevelCommentArr != null){
        for (let i = 0; i < twoLevelCommentArr.length; i ++){
            twoLevelHtmlArr.push(getTwoLevelCommentHtml(twoLevelCommentArr[i]));
        }
    }
    let readMoreReply = '<div id="moreReply_' + commentId + '" onclick="listTwoLevelComment(this)" class="topic read-more">查看更多回复>></div>',
    cs =
    '<div id="' + commentId + '" replyTotal="' + commentObj.replyTotal + '" class="comment-obj">' +
        '<div class="vent-user">' +
            '<a href="hisHome.html?' + cUserId + '">' +
            '<img class="head-img" width=48" height="48" alt="头像" src="../staticFile/images/index/maleHead.png">' +
            '<span id="' + cUserId + '" class="user-name">' + commentObj.userNick + '</span>' +
            '</a>' +
            '评论于<span>' + commentObj.createTime +'</span>' +
        '</div>' +
        '<div class="comment-text">' + commentObj.content + '</div>' +
        '<div class="operate">' +
            '<a onclick="likeForComment(this,' + commentId + ')" class="like-bg ' + getCommentLikeClass(commentObj.userLikeNum) + '">赞&nbsp;(<i>' + commentObj.likeTotal + '</i>)</a>' +
            '<a id="btnReply' + commentId + '" class="reply-bg" onclick="showReplyComment(this,' + JSON.stringify(commentObj).replace(/\"/g,"'") + ')">回复</a>' +
        '</div>' +
        '<div id="replyList' + commentId + '" class="reply-list">' + twoLevelHtmlArr.join('') +
        (commentObj.replyTotal > 0 ? readMoreReply : '') +
        '</div>' +
    '</div>';
    $('#moreComment').before(cs);
}
/**
 * 添加2级评论HTML
 * @param commentObj 2级评论对象
 */
function appendTwoLevelComment(twoLevelObj) {
    let replyCommentId = twoLevelObj.replyCommentId,parentCommentId = twoLevelObj.parentCommentId,
        twoLevelHtml = getTwoLevelCommentHtml(twoLevelObj),isReplyOneLevel = replyCommentId == 0,
        btnReplyId = isReplyOneLevel ? parentCommentId : replyCommentId;
    $('.reply-write').remove();
    $('#btnReply' + btnReplyId).removeClass('replying');
    //如果是回复一级评论
    if (isReplyOneLevel){
        let replyList = $('#replyList' + parentCommentId), moreReply = $('#moreReply' + parentCommentId);
        replyList.show();
        //如果存在“查看更多回复>>”，则加在它之前
        if (moreReply.length > 0){
            moreReply.before(twoLevelHtml);
        }else {
            replyList.children('div:last-child').before(twoLevelHtml);
        }
        return;
    }
    $('#' + replyCommentId).after(twoLevelHtml);
}

/**
 * 获取二级评论HTML
 * @param twoLevelObj 二级评论对象
 * @returns {string} 返回二级评论的html
 */
function getTwoLevelCommentHtml(twoLevelObj) {
    if (isNull(twoLevelObj)){
        return '';
    }
    let commentId = twoLevelObj.id, replyUserNick = twoLevelObj.replyCommentUserNick,
        userNick = twoLevelObj.userNick, replierSpan = '<span class="replier">' + userNick + '：</span>';

    //如果被回复的用户不为空，则说明此评论是对replyUserNick的回复
    if (!isNull(replyUserNick)){
        replierSpan = '<span class="replier">' + userNick + '<label>回复</label>' + replyUserNick + '：</span>';
    }
    return '<div id="' + commentId + '" class="reply-obj">' +
        '   <div class="reply-content">' + replierSpan + twoLevelObj.content + '</div>' +
        '   <div class="operate" style="margin-left: 0;">' +
        '       <a onclick="likeForComment(this,' + commentId + ')" class="like-bg ' +
                    getCommentLikeClass(twoLevelObj.userLikeNum) + '">赞&nbsp;(<i>' + twoLevelObj.likeTotal + '</i>)</a>' +
        '       <a id="btnReply' + commentId + '" class="reply-bg" onclick="showReplyComment(this,' + JSON.stringify(twoLevelObj).replace(/\"/g,"'") + ')">回复</a>' +
        '       <span class="reply-date">' + twoLevelObj.createTime + '</span>' +
        '   </div>' +
        '</div>';
}
function getCommentLikeClass(userLikeNum) {
    return userLikeNum > 0 ? 'comment-liked' : '';
}
/**
 * 显示回复输入框和按钮
 * @param btnReply 回复按钮对象
 * @param co 评论对象
 */
function showReplyComment(btnReply,co) {
    $(btnReply).addClass('replying');
    let commentLevel = co.commentLevel,userId = co.userId,userNick = co.userNick,coId = co.id,
        parentCommentId = co.parentCommentId,parentCommentUserId = co.parentCommentUserId,
        replyCommentId = co.replyCommentId,replyCommentUserId = co.replyCommentUserId,
    operateDiv = $(btnReply).parent(),replyWrite = operateDiv.children('.reply-write');
    //如果是回复一级评论
    if (commentLevel == 1){
        parentCommentId = coId;
        parentCommentUserId = userId;
    }else {
        replyCommentId = coId;
        replyCommentUserId = userId;
    }
    //如果回复内容的输入框存在
    if (replyWrite.length < 1){
        let btnStr = '<button class="btn" parentCommentId="' + parentCommentId + '" commentLevel="2" ' +
            'parentCommentUserId="' + parentCommentUserId + '" replyCommentId="' + replyCommentId + '" userNick="' + userNick +
            '" replyCommentUserId="' + replyCommentUserId + '" textareaId="replyContent" onclick="submitVentComment(this)">回复</button>';
        operateDiv.append('<div class="reply-write"><textarea id="replyContent" placeholder="回复[' + userNick + ']"></textarea>' + btnStr + '</div>');
        return;
    }
    let replyContent = replyWrite.children('textarea').val();
    //如果回复内容为空
    if (isNull(replyContent)){
        replyWrite.remove();
        $(btnReply).removeClass('replying');
        return;
    }
    //如果回复内容的div隐藏了，则显示，否则隐藏
    if (replyWrite.is(':hidden')){
        replyWrite.show();
    } else {
        replyWrite.hide();
    }
}

/**
 * 加载更多二级评论
 * @param btnMoreTwoLevel 加载按钮
 */
function listTwoLevelComment(btnMoreTwoLevel) {
    let parentCommentId = btnMoreTwoLevel.id.split('_')[1],
        replyNum = $('#replyList' + parentCommentId + ' .reply-obj').length;
    setButtonStatus(btnMoreTwoLevel,true,'正加载更多回复中...');
    $.ajax({
        type: 'post',
        url : '/ventIndex/listTwoLevelComment',
        dataType: 'json',
        timeout: 12000,
        data: {
            'parentCommentId': parentCommentId,
            'ventId': ventId,
            'start': replyNum,
            'twoPageSize': 6
        },
        success: function(twoLevelList) {
            if (isNull(twoLevelList) || twoLevelList.length < 1){
                alert("没有回复数据了");
                return;
            }
            let twoLevelSize = twoLevelList.length;
            for(let g = 0; g < twoLevelSize; g ++) {
                appendTwoLevelComment(twoLevelList[g]);
            }
            setButtonStatus(btnMoreTwoLevel,false,'查看更多回复>>');
            let replyTotal = $('#' + parentCommentId).attr('replyTotal');
            //如果回复起始行+总记录数>=回复总数
            if ((replyNum + twoLevelSize) >= replyTotal){
                $(btnMoreTwoLevel).remove();
            }
        },
        error: function () {
            alert("抱歉，系统开小差了，请稍候再试");
            setButtonStatus(btnMoreTwoLevel,false,'查看更多回复>>');
        }
    });
}
/**
 * 给吐槽数据点赞
 */
function likeForComment(btnLike,commentId) {
    if ($(btnLike).hasClass('comment-liked')){
        return;
    }
    $.ajax({
        type: "POST",
        async: true,
        url: "/ventComment/saveCommentLike",
        dataType: 'json',
        data:{commentId: commentId},
        success: function (clData) {
            setCommentLike(btnLike,clData);
        },
        error: function (clData) {
            setCommentLike(btnLike,clData);
        }
    });
}
/**
 * 设置评论点赞
 * @param vlData 点赞结果
 */
function setCommentLike(btnLike,clData) {
    //如果没登录，则提示登录
    if (clData.status == -1) {
        showLogin();
        return;
    }
    let commentLikeI = $(btnLike).children('i');
    let likeTotal = commentLikeI.text();
    commentLikeI.text(parseInt(likeTotal) + 1);
    $(btnLike).addClass('comment-liked');
}
/**
 * 初始化右边的<猜您关注>吐槽数据
 */
function initFollowVent() {
    $.ajax({
        type: "POST",
        async: true,
        url: "/ventIndex/listFollowVentByMost",
        dataType: 'json',
        data:{notVentId: ventId},
        success: function (followVentList) {
            if (isNull(followVentList) || followVentList.length < 1){
                return;
            }
            let followArr = [], followLen = followVentList.length;
            for (let g = 0; g < followLen; g ++){
                let fv = followVentList[g];
                followArr.push('<div class="recommend-vent">' +
                    '<a class="rc-title" href="ventObj.html?' + fv.id + '">' + fv.title + '</a>' +
                    '<div class="rc-content">' + fv.shortContent.replace(/<[^>]+>/g,'') +'</div>' +
                '</div>');
            }
            $('.right-div').append(followArr.join(''));
        }
    });
}
/**
 * "推荐您阅读"和"推荐更多吐槽>>"
 */
function recommendMoreVent() {
    //如果没有更多了，则不再加载
    if (!isHasMore){
        return;
    }
    let btnReadMoreVent = $('#readMoreVent');
    setButtonStatus(btnReadMoreVent,true,'正加载更多推荐吐槽中...');
    $.ajax({
        type: "POST",
        async: true,
        url: "/ventIndex/recommendMoreVent",
        dataType: 'json',
        data:{notVentId: ventId, pageNo: moreVentPageNo, pageSize: commentPageSize},
        success: function (moreVentPi) {
            moreVentPageNo ++;
            isHasMore = moreVentPi.hasNextPage;
            if (isHasMore){
                setButtonStatus(btnReadMoreVent,false,'查看更多推荐吐槽>>');
            }else {
                btnReadMoreVent.removeClass('read-more').addClass('no-more').text('没有更多推荐吐槽了');
            }
            let ryr = $('#recommendYouRead'),moreVentAArr = [],moreVentList = moreVentPi.list;

            //如果"推荐您阅读"下有吐槽数据了，则添加到
            if (ryr.children('a').length > 0){
                setMoreVentHtml(moreVentList);
                return;
            }
            for (let g = 0; g < moreVentList.length; g ++){
                let mv = moreVentList[g];
                moreVentAArr.push('<a href="ventObj.html?' + mv.id + '">' + mv.title + '</a>');
            }
            ryr.append(moreVentAArr.join(''));
            $('.recommend-vent a,.vt-list a').click(function () {
                readTotalAddOne(getVentIdByA(this));
            });
            //如果本次加载的是“推荐您阅读”，再重新加载一次，获取"推荐更多吐槽>>"数据
            recommendMoreVent();
        },
        error: function() {
            alert("当前系统繁忙，请稍候再看更多推荐吐槽");
            setButtonStatus(btnReadMoreVent,false,'查看更多推荐吐槽>>');
        }
    });
}

/**
 * 添加"推荐更多吐槽>>"的HTML
 * @param moreVentList
 */
function setMoreVentHtml(moreVentList) {
    if (isNull(moreVentList) || moreVentList.length < 1){
        return;
    }
    let moreVentArr = [], imgUrl = '../staticFile/images/common/';
    for (let g = 0; g < moreVentList.length; g ++){
        let v = moreVentList[g];
        moreVentArr.push('<div class="recommend-vent">' +
            '<a href="ventObj.html?' + v.id + '">' +
            '   <div class="rc-title">' + v.title + '</div>' +
            '   <div class="rc-content">' + v.shortContent.replace(/<[^>]+>/g,'') + '</div>' +
            '</a>' +
            '<div class="other-info">' +
            '   <img class="one" width="16" height="16" title="点赞数" alt="点赞数" src="' + imgUrl + 'like.png"/>' + v.likeTotal +
            '   <img width="16" height="16" title="评论数" alt="评论数" src="' + imgUrl + 'reply.png"/>' + v.commentTotal +
            '   <img width="16" height="16" title="阅读数" alt="阅读数" src="' + imgUrl + 'eye.png"/>' + v.readTotal +
            '   <img width="16" height="16" title="城市" alt="城市" src="' + imgUrl + 'city.png"/>' + v.cityName +
            '   <img width="16" height="16" title="职业" alt="职业" src="' + imgUrl + 'vent16.png"/>' + v.occupationName +
            '   <img width="16" height="16" title="发布时间" alt="发布时间" src="' + imgUrl + 'date.png"/>' + v.createDate +// '&nbsp;(发布)' +
            '</div>' +
        '</div>');
    }
    $('#readMoreVent').before(moreVentArr.join(''));
    $('.recommend-vent a,.vt-list a').click(function () {
        readTotalAddOne(getVentIdByA(this));
    });
}
/**
 * 通过A标签获取吐槽ID
 * @param a A标签对象
 * @returns {string} 吐槽ID
 */
function getVentIdByA(a) {
    return $(a).attr('href').split('?')[1];
}